package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.constant.MessageConstant;
import com.example.dto.CustomerDTO;
import com.example.dto.CustomerLoginDTO;
import com.example.entity.Customer;
import com.example.exception.LoginFailedException;
import com.example.mapper.CustomerDao;
import com.example.properties.WeChatProperties;
import com.example.result.Result;
import com.example.service.CustomerService;
import com.example.utils.HttpClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * (Customer)表服务实现类
 *
 * @author makejava
 * @since 2024-03-12 16:46:37
 */
@Service("customerService")
public class CustomerServiceImpl implements CustomerService {
    @Resource
    private CustomerDao customerDao;

    private final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;


    @Override
    public Customer wxLogin(CustomerLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前微信用户的openid
        String openid = getOpenId(userLoginDTO.getCode());

        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            //todo 微信登录抛异常
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户
        Customer customer = customerDao.getByOpenid(openid);
        //如果是新用户，自动完成注册
        if(customer == null){
            customer = Customer.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            customerDao.insert(customer);
        }
        return customer;
    }

    private String getOpenId(String code){
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN,map);

        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Customer queryById(Long id) {
        return this.customerDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param customer 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Customer> queryByPage(Customer customer, PageRequest pageRequest) {
        long total = this.customerDao.count(customer);
        return new PageImpl<>(this.customerDao.queryAllByLimit(customer, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param customer 实例对象
     * @return 实例对象
     */
    @Override
    public Customer insert(Customer customer) {
        this.customerDao.insert(customer);
        return customer;
    }

    /**
     * 修改数据
     *
     * @param customer 实例对象
     * @return 实例对象
     */
    @Override
    public Customer update(Customer customer) {
        this.customerDao.update(customer);
        return this.queryById(customer.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.customerDao.deleteById(id) > 0;
    }

    @Override
    public Result updateInfo(CustomerDTO customerDTO) {
        Customer customer = new Customer();
        BeanUtils.copyProperties(customerDTO,customer);

        if(customerDao.update(customer)>0){
            return Result.success(customer);
        }
        else{
            return Result.error("更新失败");
        }

    }
}
